<?php

namespace app\modules\user\service;

use Yii;
use app\common\base\CommonService;
use app\common\utils\Constants;
use app\modules\user\models\Account;
use app\helpers\DatetimeHelper;

class AdminService extends CommonService
{
	const PASSWORD_PREFIX = 'eflow';
	function __construct()
	{
		parent::init();
		$this->model = new Account();
	}

	public function listUsers($superiorId)
	{
		return $this->lists([
			'fields' => ['id', 'username'],
			'condition' => ['superiorId' => $superiorId],
		]);
	}

	/**
	 * 添加用户
	 * @param superiorId 上级id
	 * @param userid 用户id
	 * @param password 用户密码
	 */
	public function createUser($superiorId, $username, $password)
	{
		// 查找数据库中用户信息
		$info = $this->info([
			'condition' => [
				'username' => $username,
			]
		]);

		// user have registered
		if (!empty($info)) {
			return parent::error('ERROR_USER_REGISTERED', '用户已注册');
		}

		$this->model->username = $username;
		$this->model->password = $this->buildPassword($password);
		$this->model->isAdmin = false;
		$this->model->superiorId = $superiorId;
		$this->model->create_timestamp = DatetimeHelper::msectime();
		$this->model->update_timestamp = DatetimeHelper::msectime();
		$this->model->save();

		return [
			'success' => 1,
		];
	}


	/** 
	 * 删除用户
	 * @param string userid
	 */
	public function deleteUser($username)
	{
		// 查找数据库中用户信息
		$info = $this->info([
			'condition' => [
				'username' => $username,
			]
		]);

		if (empty($info)) {
			return parent::error('ERROR_INVALID_USERID', '用户不存在');
		}

		$this->delete([
			'username' => $username,
		]);

		return [
			'success' => 1
		];
	}

	/**
     * 密码加密;
     *
     * @return string 加密后的密码
     */
    public function buildPassword($password)
    {
        return base64_encode(self::PASSWORD_PREFIX . $password);
    }

	/**
	 * 创建管理员
	 * @param username 管理员用户名
	 * @param password 管理员密码
	 */
	public function createadmin($username, $password)
	{
		$info = $this->info([
			'condition' => [
				'username' => $username,
			]
		]);

		// user have registered
		if (!empty($info)) {
			// @see config/response_code
			return parent::error('ERROR_USER_REGISTERED', '用户已注册');
		}
		
		$this->model->username = $username;
		$this->model->password = $this->buildPassword($password);
		$this->model->isAdmin = true;
		$this->model->create_timestamp = DatetimeHelper::msectime();
		$this->model->update_timestamp = DatetimeHelper::msectime();
		$this->model->save();

		return [
			'success' => 1
		];
	}
}
